<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hanayabuki.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","width":240,"display":"always","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="本文将利用Java语言详细讲解 并查集 相关算法. 🐱 算法概要 😺 结构性质 😸 实现结构 😹 使用条件">
<meta property="og:type" content="article">
<meta property="og:title" content="算法解读(一) - 并查集">
<meta property="og:url" content="http://hanayabuki.gitee.io/2021/01/23/%E7%AE%97%E6%B3%95%E8%A7%A3%E8%AF%BB-%E4%B8%80-%E5%B9%B6%E6%9F%A5%E9%9B%86/index.html">
<meta property="og:site_name" content="花枝丸🍥的博客">
<meta property="og:description" content="本文将利用Java语言详细讲解 并查集 相关算法. 🐱 算法概要 😺 结构性质 😸 实现结构 😹 使用条件">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-01-23T07:43:55.000Z">
<meta property="article:modified_time" content="2021-01-25T11:05:29.453Z">
<meta property="article:author" content="Hanamaru🍥Yabuki">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="LeetCode常用算法">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://hanayabuki.gitee.io/2021/01/23/%E7%AE%97%E6%B3%95%E8%A7%A3%E8%AF%BB-%E4%B8%80-%E5%B9%B6%E6%9F%A5%E9%9B%86/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>算法解读(一) - 并查集 | 花枝丸🍥的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">花枝丸🍥的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">记录自己作为CS学生的点滴</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">7</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">5</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">13</span></a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/HanaYabuki" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://hanayabuki.gitee.io/2021/01/23/%E7%AE%97%E6%B3%95%E8%A7%A3%E8%AF%BB-%E4%B8%80-%E5%B9%B6%E6%9F%A5%E9%9B%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Hanamaru🍥Yabuki">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="花枝丸🍥的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          算法解读(一) - 并查集
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-01-23 15:43:55" itemprop="dateCreated datePublished" datetime="2021-01-23T15:43:55+08:00">2021-01-23</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-01-25 19:05:29" itemprop="dateModified" datetime="2021-01-25T19:05:29+08:00">2021-01-25</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E7%AE%97%E6%B3%95/" itemprop="url" rel="index"><span itemprop="name">算法</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="本文将利用Java语言详细讲解-并查集-相关算法"><a href="#本文将利用Java语言详细讲解-并查集-相关算法" class="headerlink" title="本文将利用Java语言详细讲解 并查集 相关算法."></a>本文将利用Java语言详细讲解 <em>并查集</em> 相关算法.</h1><ol>
<li>🐱 算法概要</li>
<li>😺 结构性质</li>
<li>😸 实现结构</li>
<li>😹 使用条件</li>
</ol>
<a id="more"></a>

<h2 id="什么是并查集"><a href="#什么是并查集" class="headerlink" title="什么是并查集 ?"></a>什么是并查集 ?</h2><p>并查集, 顾名思义, 可供 <em>查询</em> 和 <em>合并</em> 的集合.<br>并查集是在算法问题中很常见的神奇数据结构, 其本身实现优美, 效率极高.</p>
<p>并查集数据域 由一个长度为 n 的整型数组, 来模拟一棵树结构. 数组的变量值代表其父节点的索引位置.</p>
<h3 id="主要操作"><a href="#主要操作" class="headerlink" title="主要操作"></a>主要操作</h3><ol>
<li><p>初始化<br>将每个节点初始化为指向自身. 通常此步骤只执行一次.</p>
</li>
<li><p>查找<br>查找元素所在根节点.</p>
</li>
<li><p>合并<br>合并两个节点所在的集合.</p>
</li>
</ol>
<h2 id="并查集有什么性质"><a href="#并查集有什么性质" class="headerlink" title="并查集有什么性质 ?"></a>并查集有什么性质 ?</h2><h3 id="理解性质"><a href="#理解性质" class="headerlink" title="理解性质"></a>理解性质</h3><ol>
<li>一个大并查集结构里包含许许多多的小集合团体;</li>
<li>每个小集合都是一个树结构, 数组的值表示他们的父节点;</li>
<li>根节点指向自身; </li>
<li>指向自身的节点数量 (根节点数目) 反映了他们的连通分量数目 (集合数目).</li>
</ol>
<h3 id="常见误区"><a href="#常见误区" class="headerlink" title="常见误区 :"></a>常见误区 :</h3><ol>
<li>并查集一般不会形成一个特别菊花的菊花图, 因为在两个菊花图被合并的时候, 新图自然而然就不是菊花图了. 但是在路径优化下, 图会在被查询的过程中逐渐菊花化;</li>
</ol>
<h2 id="并查集怎么写"><a href="#并查集怎么写" class="headerlink" title="并查集怎么写 ?"></a>并查集怎么写 ?</h2><p>并查集的实现非常优雅简洁.     </p>
<h3 id="基本实现"><a href="#基本实现" class="headerlink" title="基本实现"></a>基本实现</h3><p>以 Java 语言为例, 最基本的并查集如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UnionFind</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span>[] parent;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UnionFind</span><span class="params">(<span class="keyword">int</span> size)</span> </span>&#123;</span><br><span class="line">        parent = <span class="keyword">new</span> <span class="keyword">int</span>[size];</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;size; ++i) &#123;</span><br><span class="line">            parent[i] = i;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">find</span><span class="params">(<span class="keyword">int</span> p)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">while</span> (parent[p] != p) &#123;</span><br><span class="line">            p = parent[p];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> p;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">union</span><span class="params">(<span class="keyword">int</span> p1, <span class="keyword">int</span> p2)</span> </span>&#123;</span><br><span class="line">        parent[find(p1)] = find(p2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="可优化部分"><a href="#可优化部分" class="headerlink" title="可优化部分"></a>可优化部分</h3><ol>
<li><p>扩展操作<br>求连通分量, 和求是否在同一集合.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 求连通分量数目</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getComponents</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> n = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=parent.length; i&gt;=<span class="number">0</span>; ++i) &#123;</span><br><span class="line">        n += parent[i]==i ? <span class="number">1</span> : <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> n;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 求两点是否在同一集合内</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">query</span><span class="params">(<span class="keyword">int</span> p1, <span class="keyword">int</span> p2)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> find(p1)==find(p2);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>路径压缩<br>循环迭代求取根节点的方式可能会导致集合的路径非常长, 严重影响大量数据情况下的查询效率.<br>不建议采用迭代写法, 我们一般使用递归写法来解决, 因为递归写法可以在寻找父节点的同时适当的缩短路径, 尽可能的把所有的节点都连接在父节点上.</p>
</li>
</ol>
<p>这种做法叫做并查集的 <strong>路径压缩</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">find</span><span class="params">(<span class="keyword">int</span> p)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(p==parent[p]) &#123;</span><br><span class="line">        parent[p] = find(p);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> parent[p];</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>此种写法可以使用三元表达式压行</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">find</span><span class="params">(<span class="keyword">int</span> p)</span> </span>&#123; </span><br><span class="line">    <span class="keyword">return</span> p==parent[p] ? p : ( parent[p] = find(parent[p]) );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>个人一般喜欢使用这个写法.</p>
<p>未雨绸缪, 防止迭代产生 StackOverflowError , 这里准备了迭代写法的路径压缩</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">find</span><span class="params">(<span class="keyword">int</span> p)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> k, j, r;</span><br><span class="line">    r = p;</span><br><span class="line">    <span class="keyword">while</span>(r != parent[r]) &#123;</span><br><span class="line">        r = parent[r];</span><br><span class="line">    &#125;</span><br><span class="line">    k = p;</span><br><span class="line">    <span class="keyword">while</span>(k != r) &#123;</span><br><span class="line">        j = parent[k];</span><br><span class="line">        parent[k] = r;</span><br><span class="line">        k = j;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> r;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>垃圾写法, 晦涩难懂, 谁用谁脑壳疼.</p>
<ol start="3">
<li>按秩合并<br>我们在并查集中增加一个数组 <code>rank[size]</code> , 表示树的高度, 尽量将较长的树放在上方, 缩短总查询长度.<br>需要做的改动非常多.<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1. 声明改动</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">UnionFind</span><span class="params">(<span class="keyword">int</span> size)</span> </span>&#123;</span><br><span class="line">    parent = <span class="keyword">new</span> <span class="keyword">int</span>[size];</span><br><span class="line">    rank = <span class="keyword">new</span> <span class="keyword">int</span>[size];</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;size; ++i) &#123;</span><br><span class="line">        rank[i] = <span class="number">0</span>;</span><br><span class="line">        parent[i] = i;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 2. 合并操作改动</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">union</span><span class="params">(<span class="keyword">int</span> p1, <span class="keyword">int</span> p2)</span> </span>&#123;</span><br><span class="line">    p1 = find(p1); p2 = find(p2);</span><br><span class="line">    <span class="keyword">if</span>(p1 == p2) <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">if</span>(rank[x] &lt; rank[y]) &#123;</span><br><span class="line">        parent[x] = y;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">else</span> &#123;</span><br><span class="line">        parent[y] = x;</span><br><span class="line">        <span class="keyword">if</span>(rank[x] == rank[y]) &#123;</span><br><span class="line">            ++rank[x];</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>必要性不是很大, 因为即便存在按秩合并, 最后也会在查询过程中被路径压缩不断优化. </p>
<h2 id="并查集适用于什么情况"><a href="#并查集适用于什么情况" class="headerlink" title="并查集适用于什么情况 ?"></a>并查集适用于什么情况 ?</h2><p>并查集一般适用于 : </p>
<ol>
<li>图论问题, 用于查找图中是否有环, 计算连通分量.</li>
<li>网格类问题, 计算网格区域种类数量等.</li>
<li>集合划分类问题.</li>
<li><del>等等 (</del></li>
</ol>
<h2 id="附上-可复制粘贴的最终优化版-并查集"><a href="#附上-可复制粘贴的最终优化版-并查集" class="headerlink" title="附上 : 可复制粘贴的最终优化版 并查集"></a>附上 : 可复制粘贴的最终优化版 并查集</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">UnionFind</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span>[] parent;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">UnionFind</span><span class="params">(<span class="keyword">int</span> size)</span> </span>&#123;</span><br><span class="line">        parent = <span class="keyword">new</span> <span class="keyword">int</span>[size];</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i&lt;size; ++i) parent[i] = i;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">union</span><span class="params">(<span class="keyword">int</span> p1, <span class="keyword">int</span> p2)</span> </span>&#123; parent[find(p1)] = find(p2); &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">find</span><span class="params">(<span class="keyword">int</span> p)</span> </span>&#123; <span class="keyword">return</span> p==parent[p]?p:(parent[p]=find(parent[p])); &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
    </div>

    
    
    
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="Hanamaru🍥Yabuki 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.png" alt="Hanamaru🍥Yabuki 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Java/" rel="tag"><i class="fa fa-tag"></i> Java</a>
              <a href="/tags/LeetCode%E5%B8%B8%E7%94%A8%E7%AE%97%E6%B3%95/" rel="tag"><i class="fa fa-tag"></i> LeetCode常用算法</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/12/14/%E8%A7%A3%E6%9E%90JavaWeb%E4%B8%89%E5%A4%A7%E7%BB%84%E4%BB%B6/" rel="prev" title="解析JavaWeb三大组件">
      <i class="fa fa-chevron-left"></i> 解析JavaWeb三大组件
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/01/25/%E7%AE%97%E6%B3%95%E8%A7%A3%E8%AF%BB-%E4%BA%8C-Trie%E6%A0%91/" rel="next" title="算法解读(二) - Trie树">
      算法解读(二) - Trie树 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%9C%AC%E6%96%87%E5%B0%86%E5%88%A9%E7%94%A8Java%E8%AF%AD%E8%A8%80%E8%AF%A6%E7%BB%86%E8%AE%B2%E8%A7%A3-%E5%B9%B6%E6%9F%A5%E9%9B%86-%E7%9B%B8%E5%85%B3%E7%AE%97%E6%B3%95"><span class="nav-number">1.</span> <span class="nav-text">本文将利用Java语言详细讲解 并查集 相关算法.</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E5%B9%B6%E6%9F%A5%E9%9B%86"><span class="nav-number">1.1.</span> <span class="nav-text">什么是并查集 ?</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%BB%E8%A6%81%E6%93%8D%E4%BD%9C"><span class="nav-number">1.1.1.</span> <span class="nav-text">主要操作</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B9%B6%E6%9F%A5%E9%9B%86%E6%9C%89%E4%BB%80%E4%B9%88%E6%80%A7%E8%B4%A8"><span class="nav-number">1.2.</span> <span class="nav-text">并查集有什么性质 ?</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%90%86%E8%A7%A3%E6%80%A7%E8%B4%A8"><span class="nav-number">1.2.1.</span> <span class="nav-text">理解性质</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B8%B8%E8%A7%81%E8%AF%AF%E5%8C%BA"><span class="nav-number">1.2.2.</span> <span class="nav-text">常见误区 :</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B9%B6%E6%9F%A5%E9%9B%86%E6%80%8E%E4%B9%88%E5%86%99"><span class="nav-number">1.3.</span> <span class="nav-text">并查集怎么写 ?</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9F%BA%E6%9C%AC%E5%AE%9E%E7%8E%B0"><span class="nav-number">1.3.1.</span> <span class="nav-text">基本实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%AF%E4%BC%98%E5%8C%96%E9%83%A8%E5%88%86"><span class="nav-number">1.3.2.</span> <span class="nav-text">可优化部分</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B9%B6%E6%9F%A5%E9%9B%86%E9%80%82%E7%94%A8%E4%BA%8E%E4%BB%80%E4%B9%88%E6%83%85%E5%86%B5"><span class="nav-number">1.4.</span> <span class="nav-text">并查集适用于什么情况 ?</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%99%84%E4%B8%8A-%E5%8F%AF%E5%A4%8D%E5%88%B6%E7%B2%98%E8%B4%B4%E7%9A%84%E6%9C%80%E7%BB%88%E4%BC%98%E5%8C%96%E7%89%88-%E5%B9%B6%E6%9F%A5%E9%9B%86"><span class="nav-number">1.5.</span> <span class="nav-text">附上 : 可复制粘贴的最终优化版 并查集</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Hanamaru🍥Yabuki"
      src="/images/avatar.gif">
  <p class="site-author-name" itemprop="name">Hanamaru🍥Yabuki</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">13</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">5</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/HanaYabuki" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;HanaYabuki" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://space.bilibili.com/496956009" title="Bilibili → https:&#x2F;&#x2F;space.bilibili.com&#x2F;496956009" rel="noopener" target="_blank"><i class="fab fa-youtube fa-fw"></i>Bilibili</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Hanamaru🍥Yabuki</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>















  

  

</body>
</html>
